import axios from "axios";
import store from "@/store/index.js";
import router from "@/router";
import { Message } from "element-ui";
import Cookies from "js-cookie"

const CancelToken = axios.CancelToken;

export function httpRequest(method, url, get_params, post_params, mockType, isNotCancelAxios) {
  return new Promise((resolve, reject) => {
    const options = {
      method: method,
      url: url,
      params: get_params,
      data: post_params,
      baseURL: mockType === "proxy" ? "/proxy-api" : "/local-api",
      cancelToken: new CancelToken(function(cancel) {
        if (!isNotCancelAxios) {
          store.commit("PUSH_AXIOS_CANCELS", cancel);
        };
      })
    };
    axios.interceptors.request.use(config => {
      const csrftoken = Cookies.get('csrftoken')
      if (config.url != "/user/login" && config.url != "/user/register" && csrftoken) {
        config.headers.Authorization = "Bearer " + csrftoken;
      }
      return config;
    }, function(error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    });
    axios.interceptors.response.use((res) => {  //如果要根据请求返回的结果进行一些操作就在response中设置
      if (res && res.status === 200) {
        return Promise.resolve(res);
      }
    }, error => {
      if (error.response && error.response.status === 401) {  //token过期了直接就清空本地缓存，跳转到登陆页
        localStorage.clear();
        router.push("/login");
      } else if (error.response && error.response.status === 500) {
        Message.error(error.response.data)
      }
    });
    axios(options).then(res => {
      resolve(res);
    }).catch(e => {
      console.error(e);
      reject()
    });
  });
}

export default {
  httpRequest
};
